#include "posPickHandler.h"

#include <iostream>

#include <osg/io_utils>
#include <osg/Notify>
#include <osgViewer/CompositeViewer>
	#include <osgViewer/Viewer>

#include <sstream>

Osgis::PosPickHandler::PosPickHandler(osgText::Text* updateText):_updateText(updateText)
{

}

Osgis::PosPickHandler::~PosPickHandler()
{

}
bool Osgis::PosPickHandler::handle( const osgGA::GUIEventAdapter& ea,osgGA::GUIActionAdapter& aa )
{
	switch(ea.getEventType())
	{
	case(osgGA::GUIEventAdapter::DOUBLECLICK):
		{
			osgViewer::View* view = dynamic_cast<osgViewer::View*>(&aa);
			if (view)
				pick(view,ea);
			return false;
		}   
	default:
		return false;
	}
}

void Osgis::PosPickHandler::pick( osgViewer::View* view, const osgGA::GUIEventAdapter& ea )
{
	osgUtil::LineSegmentIntersector::Intersections intersections;

	std::string gdlist="";
	float x = ea.getX();
	float y = ea.getY();
	if (view->computeIntersections(x, y, intersections))
	{
		for(osgUtil::LineSegmentIntersector::Intersections::iterator hitr = intersections.begin();
			hitr != intersections.end();
			++hitr)
		{
			std::ostringstream os;
			os<<"x("<< hitr->getWorldIntersectPoint().x()<<")"
				<<" y("<< hitr->getWorldIntersectPoint().y()<<")"
				<<" z("<< hitr->getWorldIntersectPoint().z()<<")";
			const osgUtil::LineSegmentIntersector::Intersection::IndexList& vil = hitr->indexList;
			gdlist += os.str();
			break;
		}
	}
	setLabel(gdlist);
}

void Osgis::PosPickHandler::setLabel( const std::string& name )
{
	if (_updateText.get()) 
		_updateText->setText(name);
}
